/*
 *  Copyright 2011 derek.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.aocore.util;

/**
 *
 * @author derek
 */
public class ByteConverter
{
    public static int getBytePosition(byte[] data, int val, int offset)
    {
        for (int i = offset; i < data.length; i++)
        {
            if (data[i] == val)
            {
                return i;
            }
        }

        return -1;
    }

    public static int getByteOffset(byte[] data, int val, int offset, int length)
    {
        for (int i = 0; i < length; i++)
        {
            if (data[i + offset] == val)
            {
                return i;
            }
        }

        return -1;
    }

    public static int getByteOffset(byte[] data, int val, int offset)
    {
        return getByteOffset(data, val, offset, data.length - offset);
    }

    public static String getString(byte[] data, int position, byte terminator)
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = position; i < data.length; i++)
        {
            if (data[i] == terminator)
            {
                break;
            }

            stringBuilder.append((char) data[i]);
        }

        return stringBuilder.toString();
    }

    public static String getString(byte[] data, int position, int length)
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < length; i++)
        {
            stringBuilder.append((char) data[position + i]);
        }

        return stringBuilder.toString();
    }

    public static String getString(byte[] data, int position)
    {
        return getString(data, position, (byte)0x00);
    }

    public static String getString(byte[] data)
    {
        return getString(data, 0, (byte)0x00);
    }
}
